use std::sync::Arc;
use actix_web::{HttpResponse, Result};
use actix_web::web::Data;
use crate::repositories::user_repository::UserRepository;
use log::{info, error};
use sea_orm::DatabaseConnection;

/// user service layer
pub struct UserService;

impl UserService {
    /// get all users
    pub async fn get_all_users(db: Data<Arc<DatabaseConnection>>) -> Result<HttpResponse> {
        info!("Handling request to get all users");
        match UserRepository::find_all(&db).await {
            Ok(users) => {
                info!("Successfully retrieved users");
                Ok(HttpResponse::Ok().json(users))
            },
            Err(e) => {
                error!("Failed to retrieve users: {:?}", e);
                Ok(HttpResponse::InternalServerError().json("Failed to retrieve users"))
            }
        }
    }

    /// delete user by id
    pub async fn delete_user_by_id(db: Data<Arc<DatabaseConnection>>, id: i64) -> Result<HttpResponse> {
        info!("Handling request to delete user with id: {}", id);
        match UserRepository::delete_by_id(&db, id).await {
            Ok(true) => {
                info!("Successfully deleted user with id: {}", id);
                Ok(HttpResponse::Ok().json("User deleted successfully"))
            },
            Ok(false) => {
                info!("User with id {} not found", id);
                Ok(HttpResponse::NotFound().json("User not found"))
            },
            Err(e) => {
                error!("Failed to delete user: {:?}", e);
                Ok(HttpResponse::InternalServerError().json("Failed to delete user"))
            }
        }
    }
}